package com.liu.controller;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.liu.pojo.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Controller
public class UserController {
    @RequestMapping("/j1")
    @ResponseBody//他就不会走视图解析器,会直接返回一个字符串
     public String json1() throws JsonProcessingException {
//        创建一个对象
        User user = new User(1,"程子冉",20);
//    jackson ObjectMapping 将对象转换为json格式的数据
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(user);
        return s;
     }
    @RequestMapping("/j2")
    @ResponseBody//他就不会走视图解析器,会直接返回一个字符串
    public String json2() throws JsonProcessingException {
//        创建多个对象
        User user1 = new User(1,"程子冉",20);
        User user2 = new User(2,"程子冉",20);
        User user3 = new User(3,"程子冉",20);
        User user4 = new User(4,"程子冉",20);
        User user5 = new User(5,"程子冉",20);
        List<User> list =new ArrayList<User>();
        list.add(user1);
        list.add(user2);
        list.add(user3);
        list.add(user4);
        list.add(user5);
//    jackson ObjectMapping 将对象转换为json格式的数据
        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(list);
        return s;
    }
    @RequestMapping("/j3")
    @ResponseBody//他就不会走视图解析器,会直接返回一个字符串
    public String json3() throws JsonProcessingException {
        Date date = new Date();

//    jackson ObjectMapping 将对象转换为json格式的数据
        ObjectMapper objectMapper = new ObjectMapper();
//objectMapper 时间解析后的默认格式为:Timestamp,时间戳
//        自定义时间格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = simpleDateFormat.format(date);
        return      objectMapper.writeValueAsString(format);
    }
    @RequestMapping("/j4")
    @ResponseBody//他就不会走视图解析器,会直接返回一个字符串
    public String json4() throws JsonProcessingException {
//        创建多个对象
        List<User> list =new ArrayList<User>();
        User user1 = new User(1,"程子冉",20);
        User user2 = new User(2,"程子冉",20);
        User user3 = new User(3,"程子冉",20);
        User user4 = new User(4,"程子冉",20);
        User user5 = new User(5,"程子冉",20);

        list.add(user1);
        list.add(user2);
        list.add(user3);
        list.add(user4);
        list.add(user5);
        String s = JSON.toJSONString(list);
        return s;
    }
}
